﻿
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;



using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace VtcPositionDemo.Common.Utils
{

    public class HttpUtils
    {


        public static int CON_TIME_OUT = 2000;

        public static string Get(string url)
        {
            String result = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = CON_TIME_OUT;
            HttpWebResponse response;
            try
            {
                //request.Headers.Add("token", ConfigUtil.token);
                response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }
            catch (WebException ex)
            {
                LogUtil.LogError(ex.ToString());
                string message = ex.Message;
                return ResultUtil.ErrorResultStr(-1, message);
            }
          
        }

        public static string Post(string Url, string Data)
        {
            try
            {
                if (Data == null)
                {
                    Data = "{}";
                }
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.Timeout = CON_TIME_OUT;
                byte[] bytes = Encoding.UTF8.GetBytes(Data);
                request.ContentType = "application/json";
                request.ContentLength = bytes.Length;
                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(bytes, 0, bytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();

                myStreamReader.Close();
                myRequestStream.Close();

                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                return retString;
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ex.ToString());
                string message = ex.Message;
                return ResultUtil.ErrorResultStr(-1, message);
            }
        }

        public static string Upload(String url, String file,string gmtLastModified)
        {
            try
            {
                String rootPath =ConfigUtil.rootPath;
                if (file != null && file.LastIndexOf(rootPath) == -1)
                {

                    return ResultUtil.ErrorResultStr(-1, "文件不存在或非同步目录");
                }
                string localPath = file.Replace(rootPath, "");
                //边界
                string boundary = DateTime.Now.Ticks.ToString("x");
                HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(url);
                uploadRequest.Timeout = CON_TIME_OUT;
                uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
   
                uploadRequest.Method = "POST";
                uploadRequest.Accept = "*/*";
                uploadRequest.KeepAlive = true;
                uploadRequest.Headers.Add("Accept-Language", "zh-cn");
                uploadRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                uploadRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;


                WebResponse response;
                //创建一个内存流
                Stream memStream = new MemoryStream();

                //确定上传的文件路径
                if (!String.IsNullOrEmpty(file))
                {
                    boundary = "--" + boundary;

                    //添加上传文件参数格式边界
                    string paramFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n";
                    NameValueCollection param = new NameValueCollection();
                    param.Add("localPath", localPath);
                    param.Add("gmtLastModified", gmtLastModified);
                    //写上参数
                    foreach (string key in param.Keys)
                    {
                        string formitem = string.Format(paramFormat, key, param[key]);
                        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                        memStream.Write(formitembytes, 0, formitembytes.Length);
                    }

                    //添加上传文件数据格式边界
                    string dataFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
                    string header = string.Format(dataFormat, "file", Path.GetFileName(file));
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    memStream.Write(headerbytes, 0, headerbytes.Length);

                    //获取文件内容
                    FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;

                    //将文件内容写进内存流
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                    fileStream.Close();

                    //添加文件结束边界
                    byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n\n" + boundary + "\r\nContent-Disposition: form-data; name=\"Upload\"\r\n\nSubmit Query\r\n" + boundary + "--");
                    memStream.Write(boundarybytes, 0, boundarybytes.Length);

                    //设置请求长度
                    uploadRequest.ContentLength = memStream.Length;
                    //获取请求写入流
                    Stream requestStream = uploadRequest.GetRequestStream();


                    //将内存流数据读取位置归零
                    memStream.Position = 0;
                    byte[] tempBuffer = new byte[memStream.Length];
                    memStream.Read(tempBuffer, 0, tempBuffer.Length);
                    memStream.Close();

                    //将内存流中的buffer写入到请求写入流
                    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                    requestStream.Close();
                }

                //获取到上传请求的响应
                response = uploadRequest.GetResponse();

                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();

                myStreamReader.Close();


                if (response != null)
                {
                    response.Close();
                }

                return retString;

            }
            catch (Exception ex)
            {
                LogUtil.LogError(ex.ToString());
                string message = ex.Message;
                return ResultUtil.ErrorResultStr(-1,message);
            }



        }



        public static T Get<T>(string url)
        {
            string s = Get(url);
            var JsonObj = JsonConvert.DeserializeObject<T>(s);
            return JsonObj;
        }


        public static T POST<T>(string url, JObject data)
        {
            string s = Post(url, data.ToString());
            var JsonObj = JsonConvert.DeserializeObject<T>(s);
            return JsonObj;
        }


        ///<summary>
        /// 下载文件
        /// </summary>
        /// <param name="URL">下载文件地址</param>
        /// <param name="Filename">下载后另存为（全路径）</param>
        public static int DownloadFile(string url, string localPath)
        {
            try
            {
                HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
         
                Myrq.Timeout = CON_TIME_OUT;
                HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                Stream st = myrp.GetResponseStream();
                string dir =new FileInfo(localPath).DirectoryName;
                bool v = Directory.Exists(dir);
                if (!v)
                {
                    Directory.CreateDirectory(dir);
                }
                Stream so = new System.IO.FileStream(localPath, System.IO.FileMode.Create);
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
                myrp.Close();
                Myrq.Abort();
                return 0;
            }
            catch (System.Exception e)
            {
                LogUtil.LogError(e.ToString());
                return 1;
            }
        }


    }


}
